const multer = require('multer');
const path = require('path');
const fs = require('fs-extra');

// 创建通用上传配置
function createUpload(options = {}) {
  const config = {
    storagePath: 'uploads',
    allowedTypes: ['image/*'],
    limits: { fileSize: 5 * 1024 * 1024 },
    ...options
  };

  const storage = multer.diskStorage({
    destination: async (req, file, cb) => {
      const dest = path.resolve(config.storagePath);
      await fs.ensureDir(dest);
      cb(null, dest);
    },
    filename: (req, file, cb) => {
      const ext = path.extname(file.originalname);
      cb(null, `${Date.now()}${ext}`);
    }
  });

  const fileFilter = (req, file, cb) => {
    if (config.allowedTypes.some(type => file.mimetype.startsWith(type.replace('/*', '')))) {
      cb(null, true);
    } else {
      cb(new Error('文件类型不支持'));
    }
  };

  return multer({ storage, fileFilter, limits: config.limits });
}

module.exports = { createUpload };